package logic

import (
	"context"
	"douban_srv/douban"
	"douban_srv/internal/svc"
	"douban_srv/models/cache"
	"douban_srv/models/mysql"
	"fmt"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShoppingAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShoppingAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShoppingAddLogic {
	return &ShoppingAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 购物车添加
func (l *ShoppingAddLogic) ShoppingAdd(in *douban.ShoppingAddRequest) (*douban.ShoppingAddResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var s mysql.Shopping
	if err = s.GetShoppingBy(int(in.ShopId)); err != nil {
		return nil, err
	}

	if s.ID == 0 {
		return nil, fmt.Errorf("商品不存在")
	}

	if s.Stock < int(in.Num) {
		return nil, fmt.Errorf("商品库存不足")
	}

	key := fmt.Sprintf("cart:%d:%d", in.ShopId, in.UserId)

	exists := cache.Rdb.Exists(l.ctx, key).Val()
	fmt.Println("商品是否在购物车中", exists)
	if exists == 1 {
		fmt.Println("商品在购物车中")
		if err = cache.Rdb.HIncrBy(l.ctx, key, "num", in.Num).Err(); err != nil {
			return nil, err
		} else {
			fmt.Println("商品不在购物车中")
			shoppingMap := map[string]interface{}{
				"shop_id": in.ShopId,
				"num":     in.Num,
				"name":    s.Name,
				"desc":    s.Desc,
				"price":   s.Price,
				"checked": 1,
			}
			cache.Rdb.HMSet(l.ctx, strconv.FormatInt(in.ShopId, 10), in.UserId, shoppingMap)
		}
	}
	return &douban.ShoppingAddResponse{}, nil
}
